﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace App2Wpf.Views
{
    /// <summary>
    /// RemoteWindow.xaml 的交互逻辑
    /// </summary>
    public partial class WPFWindow : Window
    {

        //全局单例 不适用 
        //private static readonly Lazy<WPFWindow> m_Lazy = new Lazy<WPFWindow>(() =>
        //{
        //    WPFWindow _Instance = new WPFWindow();
        //    _Instance.Initialize();
        //    return _Instance;
        //});

        //public static WPFWindow Instance { get => m_Lazy.Value; }

        public WPFWindow()
        {
            InitializeComponent();
            //Initialize();
        }

        private void Initialize()
        {
            App.Current.Dispatcher.Invoke(() => {

                ////画布
                m_bitmapSource = new RenderTargetBitmap(
                1920,
                1080,
                96,
                96,
                PixelFormats.Pbgra32);

                // 创建一个DrawingVisual对象
                _drawingVisual = new DrawingVisual();

                _remoteImage.Source = m_bitmapSource;

            });
        }

        public delegate void closeingWindowHandle();

        public event closeingWindowHandle theOnClosing;

        public BitmapSource m_bitmapSource;

        public DrawingVisual _drawingVisual = new DrawingVisual();

        public ViewerBase view;

        public System.IO.MemoryStream ms;
        public byte[] blockBuffer;
        public Point destPoint;

        public static Task renderTask ;


        //public void startTask(bool IsShow)
        //{
        //    renderTask = new Task(()=>startShow());
        //    renderTask.Start();
        //}
        public void startShow(bool IsShow = false)
        {
            if (null == m_bitmapSource) return;
            //App.Current.Dispatcher.Invoke(() =>
            //{
            //    if (this.Visibility != Visibility.Visible) this.Visibility = Visibility.Visible;

            //    using (DrawingContext drawingContext = _drawingVisual.RenderOpen())
            //    {
            //        drawingContext.DrawImage(m_bitmapSource, new System.Windows.Rect(destPoint.X, destPoint.Y, m_bitmapSource.PixelWidth, m_bitmapSource.PixelHeight));
            //    }
            //    (m_bitmapSource as RenderTargetBitmap).Render(_drawingVisual);

            //    _remoteImage.Source = m_bitmapSource;
            //});
            _remoteImage.Source = m_bitmapSource;
        }
        /// <summary>
        /// 窗体自带关闭事件，未采用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            theOnClosing();
            e.Cancel = true;  ////取消关闭
            this.Visibility = System.Windows.Visibility.Collapsed; ////隐藏
        }
        
        private void close_Button_Click(object sender, RoutedEventArgs e)
        {
            theOnClosing();
            this.Visibility = System.Windows.Visibility.Collapsed; ////隐藏
        }

        private void Minimized_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
        private void Maxmized_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
                this.WindowState = WindowState.Normal;
        }
        private void Title_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }


        private void _remoteImage_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this._remoteImage.Focus();
            view.SendVirtualMouse((int)e.GetPosition(_remoteImage).X, (int)e.GetPosition(_remoteImage).Y, MouseState.Down, e.ChangedButton.ToString());
        }

        private void _remoteImage_MouseUp(object sender, MouseButtonEventArgs e)
        {
            view.SendVirtualMouse((int)e.GetPosition(_remoteImage).X, (int)e.GetPosition(_remoteImage).Y, MouseState.Up, e.ChangedButton.ToString());

        }

        private void _remoteImage_MouseMove(object sender, MouseEventArgs e)
        {
            //按下时可拖动
            if(e.LeftButton == MouseButtonState.Pressed)
            view.SendVirtualMouse((int)e.GetPosition(_remoteImage).X, (int)e.GetPosition(_remoteImage).Y, MouseState.Move, "");

        }

        private void _remoteImage_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            view.WPF_logic_MouseWheel(sender, e);
        }

        private void _remoteImage_KeyDown(object sender, KeyEventArgs e)
        {
            bool isCapsLockOn = System.Windows.Forms.Control
                                 .IsKeyLocked(System.Windows.Forms.Keys.CapsLock);
            bool isShiftKeyPressed = (Keyboard.Modifiers & ModifierKeys.Shift)
                                         == ModifierKeys.Shift;
            bool isControlKeyPressed = (Keyboard.Modifiers & ModifierKeys.Control)
                                         == ModifierKeys.Control;
            if (!isCapsLockOn && !isShiftKeyPressed && e.Key >= Key.A && e.Key <= Key.Z)
            {
                string abc_keyStr = e.Key.ToString().ToLower();
                view.SendVirtualKeyboard(abc_keyStr);
                return;
            }
            //// 输入法切换 control + shift
            if (isShiftKeyPressed && isControlKeyPressed)
            {
                view.SendVirtualKeyboard("(^+)");
                return; 
            }
            //////中英文 括起来 表示一起按
            if (isControlKeyPressed && Keyboard.IsKeyDown(Key.Space))
            {
                view.SendVirtualKeyboard("(^ )");
                return;
            }
            if (isControlKeyPressed && Keyboard.IsKeyDown(Key.A))
            {
                view.SendVirtualKeyboard("(^a)");
                return;
            }
            //这里不处理组合键 输入字符

            //// 方法内部  down 平替 press
            view.WPF_logic_KeyDown(sender, e);
        }

        private void _remoteImage_KeyUp(object sender, KeyEventArgs e)
        {

        }

        private void _remoteImage_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key >= Key.A && e.Key <= Key.Z)
            {
                char lowercaseLetter = (char)('a' + (e.Key - Key.A));
                // 处理小写字母
                // 可以在此处编写你要执行的逻辑，例如将字母添加到一个文本框中
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            string key = e.Key.ToString();
            bool isCapsLockOn = System.Windows.Forms.Control
                                 .IsKeyLocked(System.Windows.Forms.Keys.CapsLock);
            bool isShiftKeyPressed = (Keyboard.Modifiers & ModifierKeys.Shift)
                                         == ModifierKeys.Shift;
            if (!isCapsLockOn && !isShiftKeyPressed)
            {
                key = key.ToLower();
            }
        }

        /// <summary>
        /// 重写 键盘事件，  转换组合按键输入的字符
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            base.OnPreviewTextInput(e);
            clientFunc.Showlog(String.Format("{0}",e.Text));
            if (Map.WPF_TextKeyMap.ContainsKey(e.Text))
            {
                string SendKey = Map.WPF_TextKeyMap[e.Text];
                view.SendVirtualKeyboard(SendKey);
            }
        }

        protected override void OnRenderSizeChanged(SizeChangedInfo info)
        {
            base.OnRenderSizeChanged(info);
            clientFunc.Showlog(String.Format("{0}×{1}", _remoteImage.ActualWidth, _remoteImage.ActualHeight));
            view.session.ViewerConfiguration.ScreenX_Ratio = view.session.ViewerConfiguration.RemoteDesktopWidth / (float)_remoteImage.ActualWidth;
            view.session.ViewerConfiguration.ScreenY_Ratio = view.session.ViewerConfiguration.RemoteDesktopHeight / (float)_remoteImage.ActualHeight;
            clientFunc.Showlog(String.Format("Ratio\r\n\r\n{0} : {1}", view.session.ViewerConfiguration.ScreenX_Ratio, view.session.ViewerConfiguration.ScreenY_Ratio));
        }
    }
}
